package com.ltu.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.sound.sampled.*;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ltu.ai.sparkdesk.websocket.AiContextManager;
import com.ltu.ai.sparkdesk.websocket.iat.IatSocketService;
import com.ltu.config.shiro.ShiroUtil;
import com.ltu.config.shiro.dto.UserDto;
import com.ltu.constant.CommonConstant;
import com.ltu.domain.mp_entity.AccountEntity;
import com.ltu.enums.CommuntiyMenDict;
import com.ltu.enums.CommuntiyMenDict.CommuntiyMenEnum;
import com.ltu.enums.EnumUtils;
import com.ltu.model.request.vo.CloudVo;
import com.ltu.model.response.CodeResp;
import com.ltu.model.response.base.CodeDataResp;
import com.ltu.service.AccountService;
import com.ltu.service.OssService;
import com.ltu.util.FileUtil;
import com.ltu.util.exception.ApiException;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import ws.schild.jave.Encoder;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.encode.AudioAttributes;
import ws.schild.jave.encode.EncodingAttributes;

@RequestMapping("/file")
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(tags = "统一文件上传接口")
public class FileUploadController {
	Logger log = org.slf4j.LoggerFactory.getLogger(FileUploadController.class);
//	private final OssService ossService;
//	private  static CloudVo   cloudVo = new CloudVo();
	
	private final IatSocketService iatSocketService;

	
	@ApiImplicitParams({
			@ApiImplicitParam(name = "businessType", value = "0:上传头像", required = true, dataType = " ", paramType = "query") })
	@ApiOperation(value = "业务文件上传")
	@PostMapping("/upload/{businessType}")
	public CodeDataResp<String> upload(@RequestPart ("file") MultipartFile uploadFile,
			@PathVariable(name = "businessType") String businessType) {
		CommuntiyMenEnum dict = EnumUtils.indexToEnum(CommuntiyMenDict.CommuntiyMenEnum.class, Integer.parseInt(businessType));
		if(dict == null && StringUtils.isNotBlank(businessType) && businessType.length()==10) {
			UserDto user =  ShiroUtil.getPrincipalUser();
			if(user.getLoginType()!=2) 
				return CodeDataResp.valueOfFailed("请使用后台管理员账号上传证书文件");
			return uploadCert(uploadFile,user,businessType);
		}
		if (dict == null )
			return CodeDataResp.valueOfFailed("请传入业务编号");
		Date date = new Date();
		// 避免文件重名
		String oldName = uploadFile.getOriginalFilename();
		String suffix = oldName.substring(oldName.lastIndexOf("."), oldName.length());// 文件名后缀
		// 获取当前项目所在的根目录
		String userDir = System.getProperties().getProperty("user.dir").concat(File.separator).concat("static");
		String uploadPath = userDir.concat(File.separator).concat(dict.getValue());
		log.info("文件上传目录：{}", uploadPath);
		// 生成文件名
		String dateStr = DateUtil.format(date, DatePattern.PURE_DATETIME_MS_PATTERN);
		String fileName = dateStr.concat("_").concat(String.valueOf(CommonConstant.ImageAddFlag.incrementAndGet()));
		fileName = fileName.concat(suffix);
		String returnPath = dict.getValue().concat("/").concat(fileName);
		log.info("返回的文件路径：{}", returnPath);
		try {
			File folder = new File(uploadPath);
			if (!folder.isDirectory())
				folder.mkdirs();
			// 文件保存
			File file = new File(folder, fileName);
            uploadFile.transferTo(file);
			//上传到阿里OSS
//                 ossService.upload(cloudVo, "static/"+returnPath,uploadPath, file);
		} catch (IOException e) {
			e.printStackTrace();
		}catch (Exception e) {
            log.error(e.getMessage());
        }

		return CodeDataResp.valueOfSuccess(returnPath);
	}
	
	@ApiImplicitParams({
		@ApiImplicitParam(name = "deviceMac", value = "设备的唯一编码", required = true, dataType = "字符", paramType = "query") })
	@ApiOperation(value = "业务文件上传")
	@PostMapping("iat/upload")
	public CodeDataResp<String> upload2(@RequestPart ("file") MultipartFile uploadFile,@RequestParam("deviceMac") String deviceMac) {
			if(!AiContextManager.IatContextMap.containsKey(deviceMac))
				return CodeDataResp.valueOfFailed("设备不存在");
		CommuntiyMenEnum dict = CommuntiyMenDict.CommuntiyMenEnum.IAT;
		if (dict == null )
			return CodeDataResp.valueOfFailed("请传入业务编号");
		Date date = new Date();
		// 避免文件重名
		String oldName = uploadFile.getOriginalFilename();
		String suffix = oldName.substring(oldName.lastIndexOf("."), oldName.length());// 文件名后缀
		// 获取当前项目所在的根目录
		String userDir = System.getProperties().getProperty("user.dir").concat(File.separator).concat("static");
		String directory = userDir.concat(File.separator).concat(dict.getValue());
		log.info("文件上传目录：{}", directory);
		// 生成文件名
		String dateStr = DateUtil.format(date, DatePattern.PURE_DATETIME_MS_PATTERN);
		String  onlyName = dateStr.concat("_").concat(String.valueOf(CommonConstant.ImageAddFlag.incrementAndGet()));
		String	sourceName = onlyName.concat(suffix);
		String	targetName = onlyName.concat(".pcm");
		String returnPath = dict.getValue().concat("/").concat(targetName);
		log.info("返回的文件路径：{}", returnPath);
		try {
			File folder = new File(directory);
			if (!folder.isDirectory())
				folder.mkdirs();
			// 文件保存
			File sourceFile = new File(folder, sourceName);
			uploadFile.transferTo(sourceFile);
//			AudioInputStream
			AudioAttributes  attribute = new AudioAttributes();
			attribute.setCodec("pcm_s16le"); //文件格式
//			attribute.setBitRate( );//编码率 
			attribute.setChannels(1);//声道：1单声道 2立体声
			attribute.setSamplingRate(16000);//采样率
			attribute.setVolume(260);//音量
			EncodingAttributes  attr = new EncodingAttributes();  
			attr.setOutputFormat("s16le");
			attr.setAudioAttributes(attribute);
			File  target = new File(folder, targetName);
			Encoder convert = new Encoder();
			convert.encode(new  MultimediaObject(sourceFile), target, attr);
			//识别音频文件
			String absolutFilePath = directory.concat(File.separator).concat(targetName );
			log.info("生成的音频文件路径：{}",absolutFilePath);
			iatSocketService.createIatClient(absolutFilePath, deviceMac);
		} catch (IOException e) {
			e.printStackTrace();
		}catch (Exception e) {
			log.error(e.getMessage());
		}
		
		return CodeDataResp.valueOfSuccess(returnPath);
	}
	
	   /**
     * 根据文件的绝对路径创建一个文件对象.
     *
     * @return 返回创建的这个文件对象
     * @since 2020-05-08
     */
    public static File createFile(String filePath) throws IOException {
        // 获取文件的完整目录
        String fileDir = FilenameUtils.getFullPath(filePath);
        // 判断目录是否存在，不存在就创建一个目录
        File file = new File(fileDir);
        if (!file.isDirectory()) {
            //创建失败返回null
            if (!file.mkdirs()) {
                throw new ApiException("文件目录创建失败...");
            }
        }
        // 判断这个文件是否存在，不存在就创建
        file = new File(filePath);
        if (!file.exists()) {
            if (!file.createNewFile()) {
                throw new ApiException("目标文件创建失败...");
            }
        }
        return file;
    }
	
	private CodeDataResp<String> uploadCert( MultipartFile uploadFile,UserDto  user,String mchId) {	
		// 避免文件重名
		String oldName = uploadFile.getOriginalFilename();
		String suffix = oldName.substring(oldName.lastIndexOf("."), oldName.length());// 文件名后缀
		// 获取当前项目所在的根目录
		String userDir = System.getProperties().getProperty("user.dir").concat(File.separator).concat("cert");
		String uploadPath = userDir;
		log.info("文件上传目录：{}", uploadPath);
		// 生成文件名
		String fileName =mchId;
		fileName = fileName.concat(suffix);
		String returnPath = "cert".concat("/").concat(fileName);
		log.info("返回的文件路径：{}", returnPath);
		try {
			File folder = new File(uploadPath);
			if (!folder.isDirectory())
				folder.mkdirs();
			// 文件保存
			uploadFile.transferTo(new File(folder, fileName));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return CodeDataResp.valueOfSuccess(oldName);
	}
	

	
	
	
	
	@ApiOperation(value = "添加水印")
	@PostMapping("/addWaterMark")
	public CodeDataResp<String> addWaterMark(@RequestParam("file") MultipartFile uploadFile
			) throws Exception {
		CommuntiyMenEnum dict = CommuntiyMenEnum.ICON;
		Date date = new Date();
		// 避免文件重名
		String oldName = uploadFile.getOriginalFilename();
		String suffix = oldName.substring(oldName.lastIndexOf("."), oldName.length());// 文件名后缀
		// 获取当前项目所在的根目录
		String userDir = System.getProperties().getProperty("user.dir").concat(File.separator).concat("static");
		String uploadPath = userDir.concat(File.separator).concat(dict.getValue());
		log.info("文件上传目录：{}", uploadPath);
		// 生成文件名
		String dateStr = DateUtil.format(date, DatePattern.PURE_DATETIME_MS_PATTERN);
		String fileName = oldName.concat("_").concat(String.valueOf(CommonConstant.ImageAddFlag.incrementAndGet()));
		fileName = oldName.concat(suffix);
		try {
			File folder = new File(uploadPath);
			if (!folder.isDirectory())
				folder.mkdirs();
			// 文件保存
			uploadFile.transferTo(new File(folder, fileName));
	
		} catch (IOException e) {
			e.printStackTrace();
		}
		dict = CommuntiyMenEnum.PDF2;
		String addWaterMarkPath = userDir.concat(File.separator).concat(dict.getValue());
		String srcPdfPath =	uploadPath.concat(File.separator).concat(fileName);
		String tarPdfPath =	addWaterMarkPath.concat(File.separator).concat(fileName);
		
		String waterMarkContent = "洲明PDF水印测试";
		FileUtil.addWaterMark( srcPdfPath, tarPdfPath, waterMarkContent, 10);
		String returnPath = dict.getValue().concat("/").concat(fileName);
		log.info("返回的文件路径：{}", returnPath);
		return CodeDataResp.valueOfSuccess(returnPath);
	}
	
	

		


}
